/*
 * @lc app=leetcode.cn id=704 lang=cpp
 *
 * [704] 二分查找
 */

// @lc code=start
class Solution {
public:
    int search(vector<int>& nums, int target) {
        //左闭右开
        int l = 0, r = nums.size();

        while (l < r) { //右开 / 右闭的区别 1. 右开不能 ==
            int middle = l + (r - l) / 2;
            if (nums[middle] > target)
                r = middle; //右开 / 右闭的区别 2. 右开为 middle, 而 右闭为 middle - 1
            
            else if (nums[middle] < target)
                l = middle + 1;
            
            else
                return middle;
        }

        return -1;
    }
};
// @lc code=end

